<?php

class MyDB extends SQLite3 {
    function __construct($file) {
        $this->open($file);
    }
    function __destruct() {
        $this->close();
    }
}

class MyCRUD {
    function __construct($file) { 
        $this->db = new MyDB($file);  
        if (! $this->db) {
            $this->db->close();
        }
    }
    function __destruct() {
        $this->db->close();
    }
    function create($table) {
        $y = array();
        $q = 'insert into ' . $table . '  (tmp) values("c");';
        $ret = $this->db->query($q);
        if (!$ret) {
            return array('error' => 'DB unable to create record');
        }
        $last = $this->db->lastInsertRowID();
        return array('id' => $last);
    }
    function read($table, $field, $data) {
        $y = array();
        $sel = ($field === null ? '' : ' where '.$field.' = "'.$data.'";');
        $q = 'select * from ' . $table . $sel;
        $ret = $this->db->query($q);
        if (!$ret) {
            return array('error' => 'DB unable to find record');
        }
        while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
            $line = array();
            foreach ($row as $key => $value) {
                $line[$key] = $value;
            }
            $y[] = $line;
        }
        return $y;
    }
    function update($table, $id, $data) {        
        $y = array();
        $q = 'select * from ' .$table . ' where id = ' . $id . ";";
        $ret = $this->db->query($q);
        if (!$ret) {
            return array('error' => 'DB unable to find record');
        }
        $q = 'update ' . $table . ' set ';
        $row = $ret->fetchArray(SQLITE3_ASSOC);
        $first = true;
        foreach ($row as $key => $value) {
            if ($key === 'id') {
                continue;
            }
            $up[$key] = $value;
            if (isset($data[$key])) {
                $value = $data[$key];
            }           
            $q = $q . ($first?'':' , ') . $key . ' = "' . $value . '" ';
            $first = false;
        }
        $q = $q . ' where id = "' . $id . '";';
        $ret = $this->db->query($q);
        if (!$ret) {
            return array('error' => 'DB unable to update record');
        }
        return $this->read($table, 'id', $id);
    }
    function delete($table, $id) {
        $q = 'delete from ' . $table . ' where id = ' . $id . ";";
        $ret = $this->db->query($q);
        if (!$ret) {
            return array('error' => 'DB unable to delete record');
        }
        return array();
    }
    private $db = null;
};

//--------------------------------------
ob_start();

$action = null;
$table = null;
$id = null;
$field = null;
$data = null;
$record = null;

$method = $_POST;

foreach ($method as $key => $value) {
    eval('$'.$key.' = "'.$value.'";');
}

$y = array('error' => null);
$c = new MyCRUD('test.db');

switch ($action) {
    
    case 'create': {
        $y = $c->create($table);
        break;
    }
    
    case 'read': {
        $y = $c->read($table, $field, $data);
        break;
    }

    case 'update': {
        unset($method['action']);
        unset($method['id']);
        $data = $method;// XXXX
        $y = $c->update($table, $id, $method);
        break;
    }

    case 'delete': {
        $y = $c->delete($table, $id);
        break;
    }
    
    case 'checktoken': {
        break;
    }

    case 'login': {
        break;
    }
    
    default: {      
    }
}

ob_end_clean();
echo json_encode($y);
return;

/*
$arg = '';
$loginfo = 'guest';
$u = null;
$p = null;
$tok = null;
$err = null;
$check = null;
$tdir = 'toks/';
$action = $_POST['action'];
if ($action === 'check') {
    $resp = 'false';
    if (isset($_POST['token'])) {
        $check = $_POST['token'];
        if(file_exists($tdir.$check)) {
           $resp = 'true'; 
        }
    }
    $y = array('response' => $resp);
    echo json_encode($y);
    return;
}
if ($action === 'login') {
    if (isset($_POST['username'])) {
        $u = $_POST['username'];
        if (isset($_POST['password'])) {
            $p = $_POST['password'];
        }
        if ($p === 'admin' && $u === 'admin') {
            / *
              $data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST']);
              $A1 = md5($data['username'] . ':' . $realm . ':' .
              $users[$data['username']]);
              $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
              $tok = md5($A1.':'.$data['nonce'].':'.strval(time()).strval(rand()).
              $data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
             * /
            $tok = md5(md5(strval(rand()) . $u . $p) . 'ssw' . md5($p . $u))
                    . md5(strval(time())) . md5(md5($p) . 'ssw'
                            . md5(md5(md5(strval(rand()) . $p))));
            file_put_contents($tdir.$tok, 'tok'); 
            $err = null;
        } else {
            $err = '**Invalid username or password**';
        }
    }
    $j = array('token' => $tok, 'error' => $err);
    echo json_encode($j);
    return;
}

*/
?>
